<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width"/>
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>聊天</title>
    <link rel="stylesheet" type="text/css" href="../../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../css/main.css" />
    <link rel="stylesheet" type="text/css" href="../../css/demo/chat.css" />

    <link rel="stylesheet" href="../../css/style.css" media="screen" type="text/css" />

</head>
<body>
  <div id="header">
      <div id="back"></div>
      <h3>@ 网易</h3>
  </div>
  <div class="btn_hide"><input type="file" name="file" id="file" value="" accept="image/*"  multiple="false"></div>
  <div id="all">
<!--       <div class="notice">
          <img src="../../image/notice.png" class="notice_img">
          <span class="notice_center">聊的不错，记得发份简历哦</span>
          <span  class="notice_right">发简历</span>
      </div> -->
      <!-- <div class="chat"> -->
          <ul class="chat-thread">
<!--             <li class="netFriend">Are we meeting today?</li>
            <li class="self">yes, what time suits you?</li>
            <li class="netFriend">yes, what time suits you?</li>
            <li class="netFriend">yes, what time suits you?</li> -->
          </ul>
     <!--  </div> -->
  </div>
  <div class="hide_confirm">
    <div class="app_sure">是否授权应用打开您的相册和相机</div>
    <div>
      <button class="sure">确认</button><button class="cancle">取消</button>
    </div>
  </div>
</body>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/jquery.js"></script>
<script type="text/javascript">
apiready=function(){
//------------------------------------------------------------
 //全局变量定义
var count=0; //获取文章api的页数
var scrollDiv2 = document.getElementsByClassName("chat-thread")[0]; //获取聊天div的元素
var faker=true;//用于判断是否置底操作的变量
var arrimgoss =new Array();
var aid=$api.getStorage("aid");//获取登陆用户ID
var jwt=$api.getStorage("jwt");
var Imgurl=new Array();
var PMaid=api.pageParam.PMaid;//获取项目经理ID
var PMname=api.pageParam.PMname;
var url_file;
var systemType = api.systemType;
//获取联系人属性
//var contactsAid=api.pageParam.aid;
//var contactsNickname=api.pageParam.nickname;
var chatRoomId=api.pageParam.chatRoomId;
//------------------------------------------------------------
//方法执行
init();
$("#header h3").html(PMname)
//initSocket(jwt);
 //------------------------------------------------------------
 //调整聊天屏幕高度
var winHeight = api.winHeight;
var height=(winHeight-110)+"px";
var all=document.getElementById("all");
all.style.height=height;
//------------------------------------------------------------
//连接服务器
var url ="http://120.77.243.176:8080/websocket/tracker?access_token=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1bml2ZXJzaXR5RmFjYWRlQXBwIiwiYXV0aCI6IlJPTEVfQURNSU4ifQ.sNly4OX36x2LSypQydW2mt48wgWislJG3UdWqaMT52KuqsNN5q2NbdzulP_E8aGiuaiqNaJncDYH-0_KZzrKcg";
var ws = new SockJS(url);
var client = Stomp.over(ws);
var headers = {};

client.connect(headers, function(){
  //alert("链接成功");
},function(){
  //alert("连接失败");
});
//------------------------------------------------------------
function subscribe() {
    var destination = "/topic/chatRoomTalking/"+chatRoomId;
    //每次服务端向客户端发送消息时，客户端都会轮流调用这个回调函数
    var subscriber = client.subscribe(destination, function(data) {
      //转化为json对象
      var datajs=eval('('+data.body+')');
      //console.log(datajs.paAdminChat.content);
      var talk_content=transText(datajs.paAdminChat.content);
      //代表的是自己发的信息<img class="headImages" src="'+ret1.list[i].user.headImagesUrl+'"/>
      if(aid==datajs.paAdminChat.aid){
        showChat_send(datajs,"mySelf","headImages_right");
      }
      //代表对方发的信息。
      if(aid!=datajs.paAdminChat.aid){
        showChat_send(datajs,"netFriend","headImages_left");
      }
      scroll_top();
    });
}
 //------------------------------------------------------------
 //发送聊天记录
 function showChat_send(data,chatClass,headImages){
       if(data.user.headImagesUrl=="#"){
         var headImagesUrl='../../image/personal_head.png'
       }else{
         var headImagesUrl=data.user.headImagesUrl;
       }
          //如果发的是图片
         // alert(data.paAdminChat.content)
        if(data.paAdminChat.content.indexOf(".jpg")>0 || data.paAdminChat.content.indexOf(".png")>0){
          var imageSrc=data.paAdminChat.content.toString().split(',')
          //alert(Imgurl.length)
         //for (var i = Imgurl.length; i >0; i--) {
          //for (var i = Imgurl.length-1; i>=0; i--) {
            $(".chat-thread").append('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'">'+'<img class="library_pic" src='+"http://"+imageSrc[0].replace(/["'"]/g,"")+'>'+"</li></div>");
          //}
         // Imgurl.splice(0,Imgurl.length); //清空数组
          //}
        }//如果发的是语音
        else if(data.paAdminChat.content.indexOf(".amr")>0){
            $(".chat-thread").append('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'"><div class="'+headImages+'_myVoice" localVocie="'+data.paAdminChat.content+'"></div></li></div>');
        }//如果发的是文字
        else{
          var talk_content=transText(data.paAdminChat.content);
          $(".chat-thread").append('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'">'+talk_content+"</li></div>");
        }
 }
 //------------------------------------------------------------
 //获取聊天记录
 function showChat(data,chatClass,headImages){
   if(data.user.headImagesUrl=="#"){
     var headImagesUrl='../../image/personal_head.png'
   }else{
     var headImagesUrl=data.user.headImagesUrl;
   }
          //如果发的是图片
        if(data.paAdminChat.content.indexOf(".jpg")>0 || data.paAdminChat.content.indexOf(".png")>0){
           var imageSrc=data.paAdminChat.content.toString().split(',')
            $(".chat-thread").prepend('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'">'+'<img class="library_pic" src='+"http://"+imageSrc[0].replace(/["'"]/g,"")+'>'+"</li></div>");
        }//如果发的是语音
        else if(data.paAdminChat.content.indexOf(".amr")>0){
            $(".chat-thread").prepend('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'"><div class="'+headImages+'_myVoice" localVocie="'+data.paAdminChat.content+'"></div></li></div>');
        }//如果发的是文字
        else{
          var talk_content=transText(data.paAdminChat.content);
          $(".chat-thread").prepend('<div class="msg"><img class="'+headImages+'" src="'+headImagesUrl+'"/><li class="'+chatClass+'">'+talk_content+"</li></div>");
        }
 }
 //------------------------------------------------------------
var UIChatBox = api.require('UIChatBox');
UIChatBox.open({
    placeholder: '',
    maxRows: 4,
    emotionPath: 'widget://image/emotion',
    texts: {
        recordBtn: {
            normalTitle: '按住说话',
            activeTitle: '松开结束'
        },
        sendBtn: {
            title: 'send'
        }
    },
    styles: {
        inputBar: {
            borderColor: '#d9d9d9',
            bgColor: '#f2f2f2'
        },
        inputBox: {
            borderColor: '#B3B3B3',
            bgColor: '#FFFFFF'
        },
        emotionBtn: {
            normalImg: 'widget://image/face.png'
        },
        extrasBtn: {
            normalImg: 'widget://image/plusSign.png'
        },
        keyboardBtn: {
            normalImg: ''
        },
        speechBtn: {
            normalImg: 'widget://image/voiceTube.png'
        },
        recordBtn: {
            normalBg: '#c4c4c4',
            activeBg: '#999999',
            color: '#000',
            size: 14
        },
        indicator: {
            target: 'both',
            color: '#c4c4c4',
            activeColor: '#9e9e9e'
        },
        sendBtn: {
            titleColor: '#4cc518',
            bg: '#999999',
            activeBg: '#46a91e',
            titleSize: 14
        }
    },
    extras: {
        titleSize: 10,
        titleColor: '#a3a3a3',
        btns: [{
            title: '图片',
            normalImg: 'widget://image/picture.png'
        }]
    }
}, function(ret, err) {
      if(ret.eventType=="send"){
          if(ret.msg){
          //点击发送文字消息
          var url='/api/oto-chats/adminChat';
          var data={
              "aid": aid,
              "chatRoom": {
                "id": chatRoomId,
                // "name": PMname,
                // "pmAid": PMaid,
                // "type": 1,
                // "userAid": aid
              },
              "content": ret.msg,
              "contentType": 1
            };
          var functionRet=function(ret){
          }
          var functionErr=function(err){
          }
          post(url,data,functionRet,functionErr);
        }
      }
      if(ret.eventType=="clickExtras" && ret.index==0){
        if(systemType=='android'){
          //安卓
          $(".hide_confirm").show();
          $(".hide_confirm .sure").click(function(){
            $(".btn_hide #file").click();
            $(".hide_confirm").hide();
          })
        }else{
          //ios
          $(".btn_hide #file").click();
        }
      }
});
//---------------------------------------------------------------------------------------------
//监听按下录音按钮
var timece=0;
var UIChatBox = api.require('UIChatBox');
UIChatBox.addEventListener({
          target : 'recordBtn',
          name : 'press'
  }, function(ret, err) {
          api.toast({         //调用测试
                  msg : '开始录音',
                  duration : 500,
                  location : 'bottom'
          });

                  timece++;
                  api.startRecord({
                     //path: '../../video'+timece+'.amr'
                  });
  });
//---------------------------------------------------------------------------------------------
//监听松开录音按钮
var UIChatBox = api.require('UIChatBox');
UIChatBox.addEventListener({
          target : 'recordBtn',
          name : 'press_cancel'
}, function(ret, err) {
          api.toast({         //调用测试
                  msg : '取消录音',
                  duration : 500,
                  location : 'bottom'
          });
    //alert(JSON.stringify(ret));
    api.stopRecord(function(ret, err) {

    });
  });
//---------------------------------------------------------------------------------------------
//监听输入框所在区域弹动事件
var UIChatBox = api.require('UIChatBox');
UIChatBox.addEventListener({
    target: 'inputBar',
    name: 'move'
}, function(ret, err) {
  //当点击输入框时 ，聊天框定位想上弹起
    var _h=ret.inputBarHeight+ret.panelHeight+"px";
    if(systemType=='android'){
      //安卓
      $("#all").css("bottom",40);
    }else{
      //ios
      document.getElementById("all").style.bottom=_h;
    }
});
//---------------------------------------------------------------------------------------------
    //表情转换
    function transText(text, imgWidth, imgHeight){
        var imgWidth = imgWidth || 30;
        var imgHeight = imgHeight || 30;
        var regx = /\[(.*?)\]/gm;
        var textTransed = text.replace(regx,function(match){
            var imgSrc = emotionData[match];
            if(!imgSrc){
                    //说明不对应任何表情，直接返回
                    return match;
            }
            var img = "<img src="+imgSrc+" width="+imgWidth+" height="+imgHeight+">";
            return img;
        });
        return textTransed;
    }

    var sourcePath = "widget://image/emotion";//表情存放目录
       getImgsPaths(sourcePath, function (emotion) {
        emotionData = emotion;
    });
    function getImgsPaths(sourcePathOfChatBox, callback){
        var jsonPath = "widget://image/emotion/emotion.json";//表情的JSON数组
        api.readFile({
            path: jsonPath
            },function(ret,err){
                if(ret.status){
                    var emotionArray = JSON.parse(ret.data);
                    var emotion = {};
                    for(var idx in emotionArray){
                            var emotionItem = emotionArray[idx];
                            var emotionText = emotionItem["text"];
                            var emotionUrl = "../../image/emotion/"+emotionItem["name"]+".png";
                            emotion[emotionText] = emotionUrl;
                    }
                    /*把emotion对象 回调出去*/
                    if("function" === typeof(callback)){
                            callback(emotion);
                    }
                }
            });
        }
//---------------------------------------------------------------------------------------------
 //定义一个当前图片索引值
  var imageBrowserIndex;
  //点击library_pic

  $(".chat-thread").on("touchstart",".library_pic",function(){
     var url=$(this).attr("src");
     imageBrowserIndex=$(this).index(".library_pic");
     openPic();
  })

  //取消授权按钮
  $(".hide_confirm .cancle").click(function(){
    $(".hide_confirm").hide();
  })
//---------------------------------------------------------------------------------------------
//点击图片查看放大效果
  //打开大图片,问题点击图片左上角的时候不能放大
  window.openPic=function(){
  var url = new Array();
  var count=arrimgoss.length;

  //遍历聊天div中 的图片，将遍历的图片路径存在数组url中
  $.each($(".library_pic"), function(i,val){
    //OSS上的图片存储
      //if($(".library_pic").eq(i).attr("src").substring(0,4)=="http"){
        url[i]=$(".library_pic").eq(i).attr("src");
      //}
      // else{

      //   count--;
      //   alert(arrimgoss[count])
      //   url.push(arrimgoss[count]);
      // }
    });
  //本地图片将其转变为网络图片存储

//   if(arrimgoss.length){
//     //for(var i=arrimgoss.length;i>0;i--){
//       for(var i=0;i<arrimgoss.length;i++){
//       //alert(arrimgoss[i-1])
// 　　    url.push(arrimgoss[i]);
//     }
//   }

    //arrimgoss
    //alert(url[imageBrowserIndex])
    var photoBrowser = api.require('photoBrowser');
    photoBrowser.open({
    images:url,
    bgColor: '#000',
    activeIndex:imageBrowserIndex,
   // placeholderImg:Imgurl
    }, function(ret, err) {
      if(ret.eventType=="click")
      {
        var photoBrowser = api.require('photoBrowser');
        photoBrowser.close();
      }
    });
 }
//---------------------------------------------------------------------------------------------
 //播放自己本地的voice
$(".chat-thread").on("touchstart",".myVoice",function(){
   var localVocie=$(this).attr("localVocie");
   //播放本地语音
   api.startPlay({
       path: localVocie
   }, function(ret, err) {
       if(ret){

       }else{
           alert("本地播放语音失败");
       }
   });
})
//oss

$(".btn_hide input").change(function(){
    //var file=$("#file")[0].files;

    //alert(file[0])
    // for(i=0;i<file.length;i++){
    // if (window.createObjcectURL != undefined) {
    //         url_file = window.createOjcectURL(file[i]);
    //     } else if (window.URL != undefined) {
    //         url_file = window.URL.createObjectURL(file[i]);
    //     } else if (window.webkitURL != undefined) {
    //         url_file = window.webkitURL.createObjectURL(file[i]);
    //     }
    //  Imgurl.push(url_file);

    // };
  //上传图片到oss
  var url='/api/oss/benyun-test-oss/postPolicy?dir=hsj/';
  var functionRet=function(ret){
    accessid = ret.accessid;
    signature = ret.signature;
    host =ret.host;
    dir =ret.dir;
    expire =ret.expire;
    policy =ret.policy;
    filesName=[];
    //组装发送数据
     for(i=0;i<$("#file")[0].files.length;i++){
    //    if (window.createObjcectURL != undefined) {
    //         url_file = window.createOjcectURL($("#file")[0].files[i]);
    //     } else if (window.URL != undefined) {
    //         url_file = window.URL.createObjectURL($("#file")[0].files[i]);
    //     } else if (window.webkitURL != undefined) {
    //         url_file = window.webkitURL.createObjectURL($("#file")[0].files[i]);
    //     }
    //  Imgurl.push(url_file);
     //Imgurl[i]=url_file;

      var request = new FormData();
      filesName[i]=new Date().getTime()+'.jpg';
      request.append("OSSAccessKeyId",accessid);//Bucket 拥有者的Access Key Id。
      request.append("policy",policy);//policy规定了请求的表单域的合法性
      request.append("signature",signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
      //---以上都是阿里的认证策略
      request.append("key",'hsj/'+filesName[i]);//文件名字，可设置路径
      request.append("success_action_status",'200');// 让服务端返回200,不然，默认会返回204
      request.append('file', $("#file")[0].files[i]);//需要上传的文件 file
      $.ajax({
              url : host,  //上传阿里地址
              data : request,
              processData: false,//默认true，设置为 false，不需要进行序列化处理
              cache: false,//设置为false将不会从浏览器缓存中加载请求信息
              async: false,//发送同步请求
              contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
         　　 type : 'post',
          　　success : function(callbackBody, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                var imageList=[];
                imageList.push('benyun-test-oss.oss-cn-shenzhen.aliyuncs.com/hsj/'+filesName[i]);
                var urlOTO='/api/oto-chats/adminChat';
                var dataOTO={
                    "aid": aid,
                    "chatRoom": {
                      "id": chatRoomId,
                      // "name": PMname,
                      // "pmAid": PMaid,
                      // "type": 1,
                      // "userAid": aid
                    },
                    "content":"'"+imageList+"'",
                    "contentType": 1
                  };
                var Ret=function(ret){
                  //for (var i = imageList.length; i>0 ; i--) {
                  //   for (var i = 0; i<imageList.length ; i++) {
                  //   //arrimgoss[i]="http://"+imageList[i].replace(/["'"]/g,"");
                  //   arrimgoss.push("http://"+imageList[i].replace(/["'"]/g,""));
                  //   //alert(arrimgoss[i-1])
                  // }

                   // alert("发送消息成功")
                }
                var Err=function(err){
                  //showProgress();
                }
                //上传图片到聊天室
                post(urlOTO,dataOTO,Ret,Err);
          },
          error : function(returndata) {
              alert(JSON.stringify(returndata));
          }
      });
    }
  }
  var functionErr=function(err){

  }
  getU(url,functionRet,functionErr);
})
//---------------------------------------------------------------------------------------------
//根据聊天室ID获取聊天记录
function gain(chatRoomId,count,faker){
  var originHeight=scrollDiv2.scrollHeight;
  var chatSizeUrl='/api/oto-chats/adminChat/page?page='+count+'&size=10&chatRoomId='+chatRoomId;
  var functionRet=function(ret1){
      //循环输出每条聊天记录
      //for (var i=(ret1.list.length-1);i>=0;i--)
      for (var i=0;i<ret1.list.length;i++)
      {
         //var talk_content=transText(ret1.list[i].paAdminChat.content);
          //代表的是用户的聊天信息<img class="headImages" src="'+ret1.list[i].user.headImagesUrl+'"/>
          if(ret1.list[i].paAdminChat.aid!=aid){
            showChat(ret1.list[i],"netFriend","headImages_left");
          }
          //代表经理的聊天信息
          if(ret1.list[i].paAdminChat.aid==aid){
            showChat(ret1.list[i],"mySelf","headImages_right");
          }
          if(faker==true){
             scroll_top();
          }else {
            scrollDiv2.scrollTop=(scrollDiv2.scrollHeight-originHeight);
          }
      }
    }
  var functionErr=function(err1){
      return false;
    }
  getU(chatSizeUrl,functionRet,functionErr);
}
//---------------------------------------------------------------------------------------------
//获取自己的aid和项目经理的aid和PMname,PMaid
function init(){
  //用户在公司页面打开跟经理聊天的情况
  if(!chatRoomId){
  var RoomUrl='/api/oto-chats/chatRoom?userAid='+aid+'&pmAid='+PMaid;
  var functionRet=function(ret){
    //获取聊天室chatroomid
    chatRoomId=ret.id;
    subscribe();
    gain(chatRoomId,count,faker);
  }
  var functionErr=function(err){
    return false;
  }
  //获取公司和职位详情
  getU(RoomUrl,functionRet,functionErr);
  }//在联系人列表打开聊天时的情况
  else if(chatRoomId){
    subscribe();
    gain(chatRoomId,count,faker);
   }
}
//---------------------------------------------------------------------------------------------
//监听滚动事件
scrollDiv2.addEventListener('scroll',winScroll,false);
function winScroll(){
  if(scrollDiv2.scrollTop==0){
    count++;
    faker=false;
    gain(chatRoomId,count,faker);
  };
}
//---------------------------------------------------------------------------------------------
//function 滚到底部
function scroll_top(){
    scrollDiv2.scrollTop=scrollDiv2.scrollHeight;
  }
  //---------------------------------------------------------------------
//   init_oss();
// var accessid='';
// var accesskey='';
// var signature='';
// var host ='';
// var expire='';
// var policy='';
// var dir='';
// var imageList=[];
function init_oss(){
  var url='/api/oss/benyun-test-oss/postPolicy?dir=hsj/';
  var functionRet=function(ret){
    accessid = ret.accessid;
    signature = ret.signature;
    host =ret.host;
    dir =ret.dir;
    expire =ret.expire;
    policy =ret.policy;
    filesName=[];
    flag=0;
    //组装发送数据
   // for(i=0;i<$("#file")[0].files.length;i++){

      var request = new FormData();
      filesName[0]=new Date().getTime()+'.jpg';
      var river={"name":"../../image/1.jpg"};
      request.append("OSSAccessKeyId",accessid);//Bucket 拥有者的Access Key Id。
      request.append("policy",policy);//policy规定了请求的表单域的合法性
      request.append("signature",signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
      //---以上都是阿里的认证策略
      request.append("key",'hsj/'+filesName[0]);//文件名字，可设置路径
      request.append("success_action_status",'200');// 让服务端返回200,不然，默认会返回204
      //request.append('file', $("#file")[0].files[i]);//需要上传的文件 file
      request.append('file',river);//需要上传的文件 file
      $.ajax({
              url : host,  //上传阿里地址
              data : request,
              processData: false,//默认true，设置为 false，不需要进行序列化处理
              cache: false,//设置为false将不会从浏览器缓存中加载请求信息
              async: false,//发送同步请求
              contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
         　　 type : 'post',
          　　success : function(callbackBody, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                //imageList.push('benyun-test-oss.oss-cn-shenzhen.aliyuncs.com/hsj/'+filesName[i]);
                flag=1;
                //alert("上传成功")
          },
          error : function(returndata) {
              alert(JSON.stringify(returndata));
          }
      });
    //}
  }
  var functionErr=function(err){

  }
  get(url,functionRet,functionErr);
}
}
//---------------------------------------------------------------------------------------------
//jquery
$(function(){
  back();
})


</script>
<script type="text/javascript" src="../../script/main.js"></script>
<script type="text/javascript" src="../../script/demo/chat.js"></script>
<script type="text/javascript" src="../../script/demo/dist/sockjs.js"></script>
<script type="text/javascript" src="../../script/demo/lib/stomp.min.js"></script>
</html>
